package io.renren.sf.controller;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.annotation.SysLog;
import io.renren.common.utils.RandomValue;
import io.renren.sf.entity.CampusEntity;
import io.renren.sf.entity.MacAddressEntity;
import io.renren.sf.entity.TeacherEntity;
import io.renren.sf.service.CampusService;
import io.renren.sf.service.MacAddressService;
import io.renren.sf.service.TeacherService;
import io.renren.sf.vo.UserBatchAddVo;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import io.renren.sf.entity.FrontUserEntity;
import io.renren.sf.service.FrontUserService;
import io.renren.common.utils.R;



/**
 *
 *
 * @author cyl_txw
 * @email cyl_txw@gmail.com
 * @date 2021-03-18 15:41:54
 */
@RestController
@RequestMapping("sf/frontuser")
public class FrontUserController {

    @Autowired
    private MacAddressService macAddressService;

    @Autowired
    private FrontUserService frontUserService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private CampusService campusService;

    /**
     * 用户数据分页
     */
    @GetMapping("/list")
    public R userPage(@RequestParam Map<String,Object> params){
        // 获取所有用户之前，先看看他们是否到期，到期则修改用户状态
        teacherService.updateStatus();
        Page<TeacherEntity> page = frontUserService.selectFrontUserEntityPage(params);
        return R.ok().put("userPage",page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{userId}")
    //@RequiresPermissions("sf:frontuser:info")
    public R info(@PathVariable("userId") Long userId){
		TeacherEntity frontUser = teacherService.getById(userId);
        return R.ok().put("frontUser", frontUser);
    }

    /**
     * 保存
     */
    @SysLog("新增用户")
    @PostMapping("/save")
    //@RequiresPermissions("sf:frontuser:save")
    public R save(@RequestBody TeacherEntity frontUser){
        Long campusId = frontUser.getCampusId();
        Date stoptime = frontUser.getStoptime();
        if(stoptime.compareTo(new Date()) < 0){
            return R.error("到期时间小于当前时间");
        }
        List<TeacherEntity> teacherEntities = new ArrayList<>();
        StringBuilder userPwd = new StringBuilder();
        Integer num = frontUser.getNum();
        for (int i = 0; i < num; i++) {
            String mobile = RandomValue.getTel();
            String password = RandomValue.getRandomNum(11);
            if(i == num - 1){
                userPwd.append("账号:" + mobile + "密码:" + password);
            }else{
                userPwd.append("账号:" + mobile + "密码:" + password + "</br>");
            }
            TeacherEntity teacherEntity = new TeacherEntity();
            teacherEntity.setCreatetime(new Date());
            teacherEntity.setCampusId(campusId);
            teacherEntity.setMacStatus(1);
            teacherEntity.setMobile(mobile);
            teacherEntity.setPassword(new BCryptPasswordEncoder().encode(password));
            teacherEntity.setStatus(1);
            teacherEntity.setStoptime(stoptime);
            teacherEntity.setUserType(2);
            teacherEntities.add(teacherEntity);
        }
        teacherService.saveBatch(teacherEntities);
        // 增加校区的总人数
        CampusEntity campusEntity = campusService.getById(campusId);
        campusEntity.setNum(campusEntity.getNum() + num);
        campusService.updateById(campusEntity);
        return R.ok().put("userPwd", userPwd);
    }

    /**
     * 批量保存
     */
    @SysLog("批量新增自定义账号用户")
    @PostMapping("/savebatch")
    public R save(@RequestBody UserBatchAddVo frontUser){
        Long campusId = frontUser.getCampusId();
        Date stoptime = frontUser.getStoptime();
        if(stoptime.compareTo(new Date()) < 0){
            return R.error("到期时间小于当前时间");
        }
        String password = new BCryptPasswordEncoder().encode(frontUser.getPassword());
        List<String> accounts = frontUser.getAccountsvo();
        List<TeacherEntity> teacherEntities = new ArrayList<>();
        StringBuilder errorUsers = new StringBuilder();
        for (int i = 0; i < accounts.size(); i++) {
            if (accounts.get(i).equals("")||accounts.get(i)==null)  continue;
            TeacherEntity teacherEntity = new TeacherEntity();
            teacherEntity.setCreatetime(new Date());
            teacherEntity.setCampusId(campusId);
            teacherEntity.setMacStatus(1);
            teacherEntity.setMobile(accounts.get(i));
            teacherEntity.setPassword(password);
            teacherEntity.setStatus(1);
            teacherEntity.setStoptime(stoptime);
            teacherEntity.setUserType(2);
            if(teacherService.getOne(new QueryWrapper<TeacherEntity>().eq("mobile",accounts.get(i)).last("limit 1"))==null)
                teacherEntities.add(teacherEntity);
            else    errorUsers.append(accounts.get(i)+",");
        }
        teacherService.saveBatch(teacherEntities);
        // 增加校区的总人数
        CampusEntity campusEntity = campusService.getById(campusId);
        campusEntity.setNum(campusEntity.getNum() + accounts.size());
        campusService.updateById(campusEntity);
        return R.ok().put("errorUsers",errorUsers);
    }

    /**
     * 修改
     */
    @SysLog("修改用户信息")
    @PostMapping("/update")
    //@RequiresPermissions("sf:frontuser:update")
    public R update(@RequestBody TeacherEntity frontUser){
        Date stoptime = frontUser.getStoptime();
        if(stoptime.compareTo(new Date()) < 0){
            return R.error("到期时间小于当前时间");
        }
        String password = frontUser.getPassword();
        if(!StringUtils.isEmpty(password)){
            // 需要修改时才去修改
            password = new BCryptPasswordEncoder().encode(password);
            frontUser.setPassword(password);
        }else{
            frontUser.setPassword(null);
        }
        if(frontUser.getStatus() == 1) {
            // 正常
            frontUser.setMacStatus(1);
        }
        teacherService.updateById(frontUser);
        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改mac状态")
    @PostMapping("/updateMacStatus")
    //@RequiresPermissions("sf:frontuser:update")
    public R updateMacStatus(@RequestBody TeacherEntity frontUser){
        teacherService.updateById(frontUser);
        return R.ok();
    }
    /**
     * 解锁mac
     */
    @PostMapping("/updateAllow")
    //@RequiresPermissions("sf:frontuser:update")
    public R updateAllow(@RequestBody MacAddressEntity macAddress){
        macAddressService.updateById(macAddress);
        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除用户")
    @PostMapping("/delete")
    //@RequiresPermissions("sf:frontuser:delete")
    public R delete(@RequestBody Long[] userIds){
        // 删除用户时候，需要将对应校区人数减一（除了体验账号）
        TeacherEntity byId = teacherService.getById(userIds[0]);
        if(byId.getUserType() != 0){
            // 非体验账号
            CampusEntity byId1 = campusService.getById(byId.getCampusId());
            byId1.setNum(byId1.getNum() - 1);
            campusService.updateById(byId1);
        }
        // 通过老师的id删除老师角色表对应记录
        teacherService.removeTeacherRoleByTid(Arrays.asList(userIds));
        teacherService.removeByIds(Arrays.asList(userIds));
        return R.ok();
    }
    /**
     * 根据用户Id查询MAC地址
     */
    @GetMapping("/getMacAddress/{userId}")
    public R getMacAddress(@PathVariable("userId") Long userId){
        List<Map<String,Object>> map = frontUserService.getMacAddress(userId);
        return R.ok().put("map",map);
    }

}
